<?php

namespace core;

class Model
{
    // 存储dao对象
    private $dao;
    // 存储表结构
    protected $fields = array();

    public function __construct()
    {
        global $config;

        $this->dao = new Dao($config['datebase']);
        // 获取表结构
        $this->getFields();
    }
    //写方法
    protected function exec(string $sql)
    {            //这个是在子类模型中调用
        return $this->dao->dao_exec($sql);
    }
    //获取ID
    public function getLastId()
    {            //这个是可能控制器调用
        return $this->dao->dao_insert_id();
    }

    //读方法
    protected function query(string $sql, $all = false)
    {
        return $this->dao->dao_query($sql, $all);
    }
    // 构造完整表名
    protected function getTable(string $table = '')
    {
        global $config;

        $table = empty($table) ? $this->table : $table;

        $table = $config['database']['prefix'] . $table;
        return $table;
    }
    // 获取当前表
    protected function getAll()
    {
        $sql = "select * from {$this->getTable()}";
        $this->query($sql);
    }
    // 获取表结构字段
    private function getFields()
    {
        $sql = "desc {$this->getTable()}";

        $rows = $this->query($sql);

        foreach ($rows as $row) {

            // 获取所有表结构
            $this->fields[] = $rows['Field'];
            // 获取主键
            if ($rows['Key'] == 'PRI') $this->fields['key'] = $rows['Field'];
        }
    }
    // 通过id获取数据
    public function getById($id){
        // 判断是否有主键名
        if(!$this->fields['key'])return false;
        $sql="select * from {$this->getTable()} where {$this->fields['key']}='{$id}'";
        return $this->query($sql);
    }
}
